package part1.task3;


import java.util.ArrayList;
import java.util.List;

public class Buffer<T> {
    private int size;
    private int startIndex;
    private int endIndex;
    private List<T> buffer;

    public Buffer(int size) {
        buffer=new ArrayList<T>(size);
        for (int i = 0; i < size; i++)
            buffer.add(null);
        this.size = size;
        startIndex=endIndex=0;
    }

    public boolean add(T t){
        int nextEndIndex=nextIndex(endIndex);
        if (nextEndIndex==startIndex)
            return false;
        else {
            endIndex=nextEndIndex;
            buffer.set(nextEndIndex,t);
            return true;
        }
    }

    public T get(){
        if (isEmpty())
            return null;
        else {
            T res=buffer.get(startIndex);
            startIndex=nextIndex(startIndex);
            return res;
        }
    }

    public boolean isEmpty(){
        return startIndex==endIndex;
    }

    private int nextIndex(int index){
        return (index+1)%size;
    }
}
